from app.extensions import get_db
from app.models.Clas import Clas
from app.models.Student import Student
from app.services.StudentService import StudentService
from fastapi import APIRouter
from fastapi.responses import JSONResponse
from app.schemas.Student import StudentSchema, StudentCreate

student_router = APIRouter(prefix="/student", tags=["学生管理"])

@student_router.get('/', summary="搜索学生")
def get_by_keyword(keyword:str=""):
    with get_db() as db:
        # 创建service对象并调用服务
        svc = StudentService(db)
        response = svc.get_by_keyword(keyword)
        return JSONResponse(
            content={
                "data": [StudentSchema.model_validate(item).model_dump() for item in response["data"]],
                "message": response["message"]
            },
            status_code=response["code"]
        )
@student_router.post("/add",summary="添加学生")
def add_student(clas_id, name, gender):
    with get_db() as db:
        # 创建service对象并调用服务
        svc = StudentService(db)
        response = svc.add_student(int(clas_id), name, gender)
        return JSONResponse(
            content={
                "data": response["data"],
                "message": response["message"]
            },
            status_code=response["code"]
        )

def get_by_id(student_id):
    """根据ID查询学生（用于修改前查看）"""
    with get_db() as db:
        svc = StudentService(db)
        return svc.get_by_id(int(student_id))

@student_router.put("/{student_id}",summary="更新学生信息")
def update_student(student_id: int, student_update: StudentCreate):
    """更新学生信息"""
    with get_db() as db:
        svc = StudentService(db)
        response = svc.update_student(int(student_id), student_update)
        return JSONResponse(
            content={
                "data": response["data"],
                "message": response["message"]
            },
            status_code=response["code"]
        )

@student_router.delete("/{student_id}", summary="删除学生信息")
def delete_student(student_id: int):
    """删除学生信息"""
    with get_db() as db:
        svc = StudentService(db)
        response =  svc.delete_student(int(student_id))
        return JSONResponse(
            content={
                "data": response["data"],
                "message": response["message"]
            },
            status_code=response["code"]
        )